package com.haohan.cloud.scm.purchase.core.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.cloud.scm.api.constant.enums.common.UseStatusEnum;
import com.haohan.cloud.scm.api.manage.entity.UPassport;
import com.haohan.cloud.scm.api.manage.feign.UPassportFeignService;
import com.haohan.cloud.scm.api.purchase.entity.*;
import com.haohan.cloud.scm.api.purchase.req.*;
import com.haohan.cloud.scm.api.purchase.resp.PurchaseEmployeeDetailResp;
import com.haohan.cloud.scm.api.purchase.trans.AddSupplierTrans;
import com.haohan.cloud.scm.api.purchase.vo.PurchaseEmployeeGoodsVO;
import com.haohan.cloud.scm.api.purchase.vo.PurchaseEmployeeSupplierVO;
import com.haohan.cloud.scm.api.supply.entity.Supplier;
import com.haohan.cloud.scm.api.sys.admin.feign.SystemUserFeignService;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.purchase.api.trans.PurchaseEntityTrans;
import com.haohan.cloud.scm.purchase.core.IScmPurchaseEmployeeInfoService;
import com.haohan.cloud.scm.purchase.service.*;
import com.haohan.cloud.scm.purchase.utils.ScmPurchaseUtils;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dy
 * @date 2019/5/17
 */
@Service
public class ScmPurchaseEmployeeInfoServiceImpl implements IScmPurchaseEmployeeInfoService {

    @Autowired
    @Lazy
    private PurchaseEmployeeService purchaseEmployeeService;
    @Autowired
    @Lazy
    private PurchaseAccountService purchaseAccountService;
    @Autowired
    @Lazy
    private PurchaseGoodsService purchaseGoodsService;
    @Autowired
    @Lazy
    private SupplierRelationService supplierRelationService;
    @Autowired
    @Lazy
    private DealRecordService dealRecordService;
    @Autowired
    @Lazy
    private UPassportFeignService uPassportFeignService;
    @Autowired
    @Lazy
    private SystemUserFeignService systemUserFeignSerivce;
    @Autowired
    @Lazy
    private ScmPurchaseUtils scmPurchaseUtils;


    /**
     * 查询采购员工详情
     *
     * @param req
     * @return
     */
    @Override
    public PurchaseEmployeeDetailResp queryEmployeeDetail(PurchaseEmployeeDetailReq req) {
        PurchaseEmployeeDetailResp resp = new PurchaseEmployeeDetailResp();
        QueryWrapper<PurchaseEmployee> query = new QueryWrapper<>();
        query.lambda()
                .eq(PurchaseEmployee::getPmId, req.getPmId())
                .eq(PurchaseEmployee::getId, req.getId());
        PurchaseEmployee employee = purchaseEmployeeService.getOne(query);
        if (!PurchaseEntityTrans.transFromEmployee(resp, employee)) {
            throw new EmptyDataException();
        }

        QueryWrapper<PurchaseAccount> queryAccount = new QueryWrapper<>();
        queryAccount.lambda()
                .eq(PurchaseAccount::getPmId, req.getPmId())
                .eq(PurchaseAccount::getAccountOwnerId, req.getId());
        PurchaseAccount account = purchaseAccountService.getOne(queryAccount);
        PurchaseEntityTrans.transFromAccount(resp, account);
        // TODO 部门信息
        return resp;
    }

    /**
     * 修改采购员工信息
     *
     * @param req
     * @return
     */
    @Override
    public Boolean modifyEmployeeDetail(PurchaseModifyEmployeeReq req) {
        QueryWrapper<PurchaseEmployee> query = new QueryWrapper<>();
        query.lambda()
                .eq(PurchaseEmployee::getPmId, req.getPmId())
                .eq(PurchaseEmployee::getId, req.getId());
        PurchaseEmployee employee = purchaseEmployeeService.getOne(query);
        if (null == employee) {
            throw new ErrorDataException("员工查询有误");
        }
        PurchaseEmployee modifyEmployee = new PurchaseEmployee();
        BeanUtil.copyProperties(req, modifyEmployee);
        // 校验 uid / userId
        checkId(modifyEmployee);
        return purchaseEmployeeService.updateById(modifyEmployee);
    }

    /**
     * 查询采购员工列表 管理商品
     *
     * @paramassaasas req
     * @return
     */
    @Override
    public Page queryEmployeeGoodsList(PurchaseEmployeeGoodsReq req) {
        Page queryPage = new Page();
        queryPage.setCurrent(req.getCurrent());
        queryPage.setSize(req.getSize());
        PurchaseGoods purchaseGoods = new PurchaseGoods();
        purchaseGoods.setPmId(req.getPmId());
        purchaseGoods.setEmployeeId(req.getEmployeeId());
        // 只查询启用状态的
        purchaseGoods.setUseStatus(UseStatusEnum.enabled.getType());
        Page page = (Page) purchaseGoodsService.page(queryPage, Wrappers.query(purchaseGoods));
        if (page.getRecords().isEmpty()) {
            throw new EmptyDataException();
        }
        List<PurchaseEmployeeGoodsVO> voList = new ArrayList<>(page.getRecords().size());
        PurchaseEmployeeGoodsVO goodsVO;
        for (Object obj : page.getRecords()) {
            PurchaseGoods pg = BeanUtil.toBean(obj,PurchaseGoods.class);
            goodsVO = new PurchaseEmployeeGoodsVO();
            BeanUtil.copyProperties(pg, goodsVO);
            // TODO　关联商品属性
            voList.add(goodsVO);
        }
        page.setRecords(voList);
        return page;
    }
    /**
     * 查询采购员工列表 管理供应商
     *
     * @param req
     * @return
     */
    @Override
    public Page queryEmployeeSupplierList(PurchaseEmployeeSupplierReq req) {
        Page queryPage = new Page();
        queryPage.setCurrent(req.getCurrent());
        queryPage.setSize(req.getSize());
        SupplierRelation supplierRelation = new SupplierRelation();
        supplierRelation.setPmId(req.getPmId());
        supplierRelation.setEmployeeId(req.getEmployeeId());
        // 只查询启用状态的
        supplierRelation.setUseStatus(UseStatusEnum.enabled);
        Page page = (Page) supplierRelationService.page(queryPage, Wrappers.query(supplierRelation));
        if (page.getRecords().isEmpty()) {
            throw new EmptyDataException();
        }
        List<PurchaseEmployeeSupplierVO> voList = new ArrayList<>(page.getRecords().size());
        PurchaseEmployeeSupplierVO supplierVo;
        for (Object obj : page.getRecords()) {
            SupplierRelation sr = BeanUtil.toBean(obj,SupplierRelation.class);
            supplierVo = new PurchaseEmployeeSupplierVO();
            BeanUtil.copyProperties(sr, supplierVo);
            // TODO　关联 供应商属性

            voList.add(supplierVo);
        }
        page.setRecords(voList);
        return page;
    }
    /**
     * 查询采购员工 资金扣减记录
     *
     * @param req
     * @return
     */
    @Override
    public Page queryEmployeeBillList(PurchaseEmployeeBillReq req) {
        QueryWrapper<PurchaseAccount> query = new QueryWrapper<>();
        query.lambda()
                .eq(PurchaseAccount::getPmId, req.getPmId())
                .eq(PurchaseAccount::getAccountOwnerId, req.getEmployeeId());
        PurchaseAccount account = purchaseAccountService.getOne(query);
        if (null == account) {
            throw new ErrorDataException();
        }
        Page queryPage = new Page();
        queryPage.setCurrent(req.getCurrent());
        queryPage.setSize(req.getSize());
        QueryWrapper<DealRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(DealRecord::getPmId, req.getPmId())
                .eq(DealRecord::getAccountId, account.getId())
                .ge(DealRecord::getDealTime, req.getBeginDealTime())
                .le(DealRecord::getDealTime, req.getEndDealTime());
        Page<DealRecord> page = (Page<DealRecord>) dealRecordService.page(queryPage, queryWrapper);
        if (page.getRecords().isEmpty()) {
            throw new EmptyDataException();
        }
        return page;
    }

    /**
     * 新增采购员工
     * @param purchaseEmployee
     *      必需参数: telephone/ name
     * @return 成功返回时员工属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<PurchaseEmployee> addPurchaseEmployee(PurchaseEmployee purchaseEmployee) {
        String telephone = purchaseEmployee.getTelephone();
        QueryWrapper<PurchaseEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PurchaseEmployee::getTelephone, telephone);
        PurchaseEmployee employee = purchaseEmployeeService.getOne(queryWrapper);
        if(null != employee){
            throw new ErrorDataException("该手机号已创建员工");
        }
        checkId(purchaseEmployee);
        purchaseEmployeeService.save(purchaseEmployee);
        return new R<>(purchaseEmployee);
    }

    /**
     * 采购员工 绑定系统用户 根据手机号
     * @param telephone 手机号
     * @return data返回PurchaseEmployee
     */
    @Override
    public R<PurchaseEmployee> relationEmployeeUser(String telephone) {
        R<PurchaseEmployee> result = RUtil.error();
        // 根据手机号查询员工
        QueryWrapper<PurchaseEmployee> queryWrapper= new QueryWrapper<>();
        queryWrapper.lambda().eq(PurchaseEmployee::getTelephone, telephone);
        List<PurchaseEmployee> employeeList = purchaseEmployeeService.list(queryWrapper);
        if(CollUtil.isEmpty(employeeList)|| employeeList.size()>1){
            result.setMsg("找不到对应员工");
            return result;
        }
        // 根据手机号查询系统user
        R<String> r = systemUserFeignSerivce.queryUserId(telephone, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(r)){
            result.setMsg("找不到对应系统用户");
            return result;
        }
        // 保存
        PurchaseEmployee employee = employeeList.get(0);
        employee.setUserId(r.getData());
        purchaseEmployeeService.save(employee);
        result.setCode(CommonConstants.SUCCESS);
        result.setData(employee);
        return result;
    }

    /**
     * 采购员工新增供应商
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addSupplier(BuyerAddSupplierReq req) {
        //新增供应商
        Supplier supplier = AddSupplierTrans.trans(req);
        Supplier addSupplier = scmPurchaseUtils.addSupplier(supplier);
        //新增采购员工管理该供应商
        SupplierRelation supplierRelation = new SupplierRelation();
        supplierRelation.setPmId(req.getPmId());
        supplierRelation.setEmployeeId(req.getUid());
        supplierRelation.setSupplierId(addSupplier.getPassportId());
        supplierRelation.setUseStatus(UseStatusEnum.enabled);
        return supplierRelationService.save(supplierRelation);
    }

    /**
     * 校验 uid / userId
     * @param purchaseEmployee
     */
    private void checkId(PurchaseEmployee purchaseEmployee){
        // 绑定通行证
        String uid = purchaseEmployee.getPassportId();
        if (StrUtil.isNotEmpty(uid)) {
            UPassport uPassport = scmPurchaseUtils.fetchUPassportById(uid);
            uid = (null == uPassport) ? "" : uid;
        }
        purchaseEmployee.setPassportId(uid);
        // 绑定系统用户
        String userId = purchaseEmployee.getUserId();
        if (StrUtil.isNotEmpty(userId)){
            userId = scmPurchaseUtils.fetchUserId(purchaseEmployee.getTelephone());
        }
        purchaseEmployee.setUserId(userId);
    }
}
